package com.badger.generator.pattern;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;
import java.util.stream.Collectors;

import com.badger.generator.constant.DataBaseDriver;
import com.badger.generator.entity.GeneratorAttr;
import com.badger.generator.enums.DataBaseFieldEnum;
import com.badger.generator.enums.DataBaseType;

/**
 * 构建生成文件所需要的表的信息以及字段信息的数据
 * @author liqi
 *
 */
public final class DmStrategy extends AbstractDataBaseStrategy {

    /**Dm 查询所有的表*/
    public static final String SELECT_TABLE = "SELECT TABLE_NAME,COMMENTS FROM USER_TAB_COMMENTS ";
    /**Dm 查询表结构字段的明细*/
    public static final String SELECT_FIELD = "SELECT A .TABLE_NAME, A.COLUMN_NAME, CASE WHEN A.DATA_TYPE='NUMBER' THEN (CASE WHEN A.DATA_PRECISION IS NULL THEN A.DATA_TYPE WHEN NVL(A.DATA_SCALE, 0) > 0 THEN A.DATA_TYPE||'('||A.DATA_PRECISION||','||A.DATA_SCALE||')' ELSE A.DATA_TYPE||'('||A.DATA_PRECISION||')' END) ELSE A.DATA_TYPE END DATA_TYPE, B.COMMENTS  FROM USER_TAB_COLUMNS A, USER_COL_COMMENTS B WHERE A.TABLE_NAME=B.TABLE_NAME AND A.COLUMN_NAME = B.COLUMN_NAME AND A.TABLE_NAME = '%s'";
    /**Dm 查询该表的主键字段*/
    public static final String SELECT_PK = "SELECT A.COLUMN_NAME FROM USER_CONS_COLUMNS A, USER_CONSTRAINTS B WHERE A.CONSTRAINT_NAME = B.CONSTRAINT_NAME AND B.CONSTRAINT_TYPE = 'P' AND A.TABLE_NAME = '%s'";
    /**
     * test
     */
    public static final String DD = "SELECT A.COLUMN_NAME, CASE WHEN A.DATA_TYPE='NUMBER' THEN "
            + "(CASE WHEN A.DATA_PRECISION IS NULL THEN A.DATA_TYPE "
            + "WHEN NVL(A.DATA_SCALE, 0) > 0 THEN A.DATA_TYPE||'('||A.DATA_PRECISION||','||A.DATA_SCALE||')' "
            + "ELSE A.DATA_TYPE||'('||A.DATA_PRECISION||')' END) "
            + "ELSE A.DATA_TYPE END DATA_TYPE, B.COMMENTS,DECODE(C.POSITION, '1', 'PRI') KEY "
            + "FROM USER_TAB_COLUMNS A INNER JOIN USER_COL_COMMENTS B ON A.TABLE_NAME = B.TABLE_NAME"
            + " AND A.COLUMN_NAME = B.COLUMN_NAME LEFT JOIN USER_CONSTRAINTS D "
            + "ON D.TABLE_NAME = A.TABLE_NAME AND D.CONSTRAINT_TYPE = 'P' "
            + "LEFT JOIN USER_CONS_COLUMNS C ON C.CONSTRAINT_NAME = D.CONSTRAINT_NAME "
            + "AND C.COLUMN_NAME=A.COLUMN_NAME WHERE A.TABLE_NAME = '%s' ORDER BY A.COLUMN_ID ";

    private DmStrategy(Connection connection, DataBaseFieldEnum fieldEnum, List<String> tables,
            List<String> includePrefix) {
        super(connection, fieldEnum, tables, includePrefix);
    }

    /**
     * @param attr
     * @return
     */
    public static AbstractDataBaseStrategy getInstance(GeneratorAttr attr) {
        try {
            Connection conn = DriverManager.getConnection(attr.getUrl(), attr.getUser(), attr.getPassword());
            Class.forName(DataBaseDriver.DM);
            return new DmStrategy(conn, DataBaseFieldEnum.DM, attr.getTables(), attr.getIncludePrefix());
        } catch (SQLException | ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    String getTableSql() {
        // dm的系统表特别多，如果有指定了生成的表，先过滤表
        StringBuilder sb = new StringBuilder(SELECT_TABLE);
        if (null != super.getTables() && !super.getTables().isEmpty()) {
            sb.append(" WHERE ").append(DataBaseFieldEnum.DM.getTableName()).append(" IN (");
            /*
             * joining(CharSequence delimiter,CharSequence prefix,CharSequence suffix)
             * 第一个参数，中间分隔符号 ;第二个参数，前缀 ;第三个参数，后缀
             * 下面结果：前缀["] 内容[0] 分隔符[","] 内容[1] 分隔符[","] 内容[2] 后缀["]
             */
            sb.append(super.getTables().stream().collect(Collectors.joining("\",\"", "'", "'")));
            sb.append(")");
        }
        return sb.toString();

    }

    @Override
    String getFieldSql(String tableName) {
        // TODO dm 还没正式完成，本地dm装失败了
        return String.format(DD, tableName);
    }

    @Override
    DataBaseType typeConvert(String fieldType) {
        return ConvertSingleFactory.getInstance().build(DataBaseDriver.DM).processTypeConvert(fieldType);
    }

}
